/**
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the GPL License, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.guardianapis.api.serialization;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import junit.framework.TestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guardianapis.api.domain.jaxb.Content;
import com.guardianapis.api.domain.jaxb.Search;
import com.guardianapis.api.domain.jaxb.Tag;
import com.guardianapis.api.domain.jaxb.Tags;
import com.guardianapis.api.domain.jaxb.TypeSpecific;
import com.guardianapis.api.util.BannerUtils;
import com.guardianapis.api.util.Dumper;

/**
 * This classes basic interaction with the content API
 * 
 * @author michael.lee
 *
 */
public class JaxbContentSerializerBase extends TestCase {

	/*******************************************************************************
	 * Constants
	 *******************************************************************************/

	private static Log log = LogFactory.getLog(JaxbContentSerializerBase.class);

	/*******************************************************************************
	 * Properties 
	 *******************************************************************************/

	private String testSearchArticleFilePath = "src/test/webapp/samples/search-article.xml";
	private String testSearchAudioFilePath = "src/test/webapp/samples/search-audio.xml";
	private String testSearchVideoFilePath = "src/test/webapp/samples/search-video.xml";
	private String testSearchGalleryFilePath = "src/test/webapp/samples/search-gallery.xml";
	private String testContentFilePath = "src/test/webapp/samples/item.xml";
	private String testTagsFilePath = "src/test/webapp/samples/tags.xml";
	protected GuardianContentSerializer serializer;
	
	/*******************************************************************************
	 * Implementing JUnit Lifecyle Methods 
	 *******************************************************************************/

	public void setUp() {
		serializer = new XStreamContentSerializer();
	}
	
	/*******************************************************************************
	 * JUnit Tests 
	 *******************************************************************************/
	
	public void testDeserializeArticleSearch() throws Exception {
		log.info(BannerUtils.generateBanner(this, "testDeserializeArticleSearch"));

		FileInputStream testSearchFile = new FileInputStream(new File(testSearchArticleFilePath));
		Search testSearch = serializer.deSerializeSearch(testSearchFile);
		Dumper.dump(testSearch);
		
		assertNotNull(testSearch);
		assertEquals(759, testSearch.getCount());
		assertEquals(2, testSearch.getStartIndex());
		assertNotNull(testSearch.getResults());
		assertNotNull(testSearch.getResults().getContent());
		
		List<Content> contentList = testSearch.getResults().getContent();
		assertEquals(20, contentList.size());
		Content firstContentItem = contentList.get(0);
		
		assertEquals(new Integer(340051235), firstContentItem.getId());
		assertEquals("article", firstContentItem.getType());
		assertEquals("http://www.guardian.co.uk/media/2008/nov/25/lesleydouglas-bbc", firstContentItem.getWebUrl());
		assertEquals("http://api.guardianapis.com/content/item/340051235", firstContentItem.getApiUrl());
		assertEquals("guardian.co.uk", firstContentItem.getPublication());
		assertEquals("Lesley Douglas to join Universal Music", firstContentItem.getHeadline());
		assertEquals("John Plunkett", firstContentItem.getByline());
		assertEquals("Media", firstContentItem.getSectionName());
		assertEquals(" Former BBC Radio 2 controller Lesley Douglas, who quit the corporation over the 'Sachsgate' affair, is to join Universal Music UK. By John Plunkett ", firstContentItem.getTrailText());
		assertEquals("Lesley Douglas to join Universal Music UK", firstContentItem.getLinkText());
		assertEquals("http://static.guim.co.uk/sys-images/Media/Pix/pictures/2008/10/28/douglas84.jpg", firstContentItem.getTrailImage());
		
		assertNotNull(firstContentItem.getTaggedWith());
		assertNotNull(firstContentItem.getTaggedWith().getTag());
		List<Tag> tagList = firstContentItem.getTaggedWith().getTag();
		assertEquals(10, tagList.size());
		Tag firstContentTag = tagList.get(0);
		
		assertEquals("Business", firstContentTag.getName());
		assertEquals("keyword", firstContentTag.getType());
		assertEquals("/business", firstContentTag.getFilter());
		assertEquals("http://api.guardianapis.com/content/search?filter=/business", firstContentTag.getApiUrl());
		assertEquals("http://www.guardian.co.uk/business", firstContentTag.getWebUrl());
		
		String firstContentItemBody = " Former BBC Radio 2 controller Lesley Douglas, who quit the corporation over the \"Sachsgate\" " +
			"affair, is to join Universal Music UK.  Douglas will become director of programming and business development at the music " + 
			"company, which has a roster of best-selling artists including Amy Winehouse, Duffy and the Killers.  She will take a dual " +
			"programming and marketing role at the company, which she will join on December 8. Douglas will take charge of Universal's " +
			"two-year-old TV division, which has produced ITV music specials featuring Elton John, Girls Aloud and Take That and has " +
			"ambitions to move into comedy and drama.  Douglas will also oversee Universal Music's UK business development strategy, " + 
			"reporting to David Joseph, the chairman and chief executive of Universal Music UK.  Joseph said Douglas would be \"at the " +
			"heart of the evolution and growth of our company\", adding that Universal's artists and staff had \"huge respect and trust " +
			"for her as a broadcaster and above all as someone who lives and breathes music\".  \"She has an exceptional rapport with " + 
			"artists and is simply one of the best media executives and leaders in the business. Lesley ... is joining us to take a dual " +
			"role which will be at the heart of the evolution and growth of our company,\" Joseph said in a message to Universal staff.  " +
			"\"As director of programming, Lesley will drive the development of Globe Productions, our fast-growing TV division. Since its " +
			"launch in 2006, Globe has had many successes including a BBC Paul Weller documentary, Bebo online drama The Secret World of " +
			"Sam King and specials for ITV featuring Elton John, Girls Aloud and Take That.  \"Under Lesley's guidance, Globe's remit will " +
			"extend beyond music properties to dramas and comedies across all media.  \"In addition Lesley will oversee Universal Music's " +
			"UK business development strategy, also reporting to me. This will include non-traditional artist rights, sponsorships and " +
			"strategic marketing partnerships such as the hugely successful pairing of Take That with Marks &amp; Spencer.   \"As we " +
			"continue to diversify our business, I am excited about what Lesley's immense experience, constantly innovative approach and " +
			"fresh perspective can bring to our biggest growth areas.\"  The Universal Music UK head of business development, Mark " +
			"Krendel, and the Globe general manager, Iain Funnell, will report to Douglas.  Douglas was formerly one of the BBC's most " +
			"senior executives and, as its head of pop, was responsible for coordinating music output across BBC TV and radio. She was " +
			"also controller of Radio 2 and BBC 6Music.  She quit at the end of last month in the wake of crisis caused by the lewd phone "+
			"messages left by Radio 2 presenters Russell Brand and Jonathan Ross on actor Andrew Sachs' voicemail as part of Brand's radio " +
			"show.  Douglas will also join Lucian Grainge, the chairman and chief executive of Universal Music Group International, who " +
			"oversees the record company's business outside of America.   Universal had a 33.5% share of the UK music market in the first " +
			"half of 2008, with a stable of artists that also includes U2, Elton John, 50 Cent and Kanye West.  On Friday, it emerged in a " +
			"BBC Trust investigation into the Sachsgate affair that Douglas approved the controversial segment for broadcast on Brand's " +
			"late-night Saturday show with a single-word email sent from her BlackBerry: \"Yes.\"  However, Douglas had not listened to the " +
			"programme before it was broadcast. Brand resigned, as did the station's head of compliance Dave Barber, while Ross was " +
			"suspended for 12 weeks without pay.   Douglas had been controller of Radio 2 since 2003, having previously been deputy to " +
			"her predecessor, Jim Moir. She was also controller of digital music station 6Music.  She was the driving force behind the " +
			"modernisation of Radio 2, the country's most popular station with more than 13 million listeners.  Douglas brought presenters " +
			"such as Chris Evans, Jeremy Vine and the man who would eventually precipitate her downfall - Russell Brand.  &#183; To contact " +
			"the MediaGuardian news desk email editor@mediaguardian.co.uk or phone 020 7239 9857. For all other inquiries please call the " +
			"main Guardian switchboard on 020 7278 2332.  &#183; If you are writing a comment for publication, please mark clearly \"for " +
			"publication\". ";
		
		assertEquals(firstContentItemBody, firstContentItem.getTypeSpecific().getBody());
		
		assertNotNull(testSearch.getFilters());
		assertNotNull(testSearch.getFilters().getTag());
		List<Tag> pageTagList = testSearch.getFilters().getTag();
		assertEquals(25, pageTagList.size());
		Tag firstPageTag = pageTagList.get(0);
		
		assertEquals("Article", firstPageTag.getName());
		assertEquals("content-type", firstPageTag.getType());
		assertEquals("/global/article", firstPageTag.getFilter());
		assertEquals("http://api.guardianapis.com/content/search?filter=/global/article", firstPageTag.getApiUrl());
		assertEquals("", firstPageTag.getWebUrl());
		assertEquals(new Integer(759), firstPageTag.getCount());
		assertEquals("http://api.guardianapis.com/content/search?content-type=article&count=20&q=music&after=20070321&before=20090306&filter=/media/radio&filter=/global/article", firstPageTag.getFilterUrl());
	}
	
	public void testDeserializeAudioSearch() throws Exception {
		log.info(BannerUtils.generateBanner(this, "testDeserializeAudioSearch"));

		FileInputStream testSearchFile = new FileInputStream(new File(testSearchAudioFilePath));
		Search testSearch = serializer.deSerializeSearch(testSearchFile);
		
		assertNotNull(testSearch);
		assertNotNull(testSearch.getResults());
		assertNotNull(testSearch.getResults().getContent());

		Content firstContentItem = testSearch.getResults().getContent().get(0);
		TypeSpecific firstContentTypeSpecific = firstContentItem.getTypeSpecific();
		assertEquals(new Integer(38), firstContentTypeSpecific.getDurationMinutes());
		assertEquals(new Integer(32), firstContentTypeSpecific.getDurationSeconds());
		
		String testShowNotes = " Welcome to another edition of Music Weekly, the pod that brings you music, chat and " +
		"a feature that we can't find a name for each and every Friday.  Our main guest this week is Antony Hegarty, " +
		"he of \"and the Johnsons\" and one of the most powerful voices in popular music. He talks to Rosie Swash " + 
		"(one of the most powerful voices in podcasting) about the new album, fame and, in heated tones, Katy Perry.  " + 
		"Rosie's also conducted ceremonies with Sway, the UK rapper who made it big with the Mobos and a Mercury " + 
		"nomination two years ago. He has since signed for Akon and has his eyes focused on cracking America.  Paul " + 
		"MacInnes is in his comfy chair where he's joined by Rosie and the sqwonkmeister Michael Hann to review new music " +
		"from Dinosaur Pile Up, Eagles of Death Metal and Amazing Baby(!).   Click on to listen to the show and please " +
		"do post your comments below ";
		assertEquals(testShowNotes, firstContentTypeSpecific.getShowNotes());
	}
	
	public void testDeserializeVideoSearch() throws Exception {
		log.info(BannerUtils.generateBanner(this, "testDeserializeVideoSearch"));

		FileInputStream testSearchFile = new FileInputStream(new File(testSearchVideoFilePath));
		Search testSearch = serializer.deSerializeSearch(testSearchFile);
		
		assertNotNull(testSearch);
		assertNotNull(testSearch.getResults());
		assertNotNull(testSearch.getResults().getContent());

		Content firstContentItem = testSearch.getResults().getContent().get(0);
		TypeSpecific firstContentTypeSpecific = firstContentItem.getTypeSpecific();
		assertEquals(new Integer(3), firstContentTypeSpecific.getDurationMinutes());
		assertEquals(new Integer(26), firstContentTypeSpecific.getDurationSeconds());
	}

	public void testDeserializeGallerySearch() throws Exception {
		log.info(BannerUtils.generateBanner(this, "testDeserializeGallerySearch"));

		FileInputStream testSearchFile = new FileInputStream(new File(testSearchGalleryFilePath));
		Search testSearch = serializer.deSerializeSearch(testSearchFile);
		
		assertNotNull(testSearch);
		assertNotNull(testSearch.getResults());
		assertNotNull(testSearch.getResults().getContent());

		Content firstContentItem = testSearch.getResults().getContent().get(0);
		TypeSpecific firstContentTypeSpecific = firstContentItem.getTypeSpecific();
		assertEquals(new Integer(10), firstContentTypeSpecific.getPictureCount());
	}

	public void testBasicDeserializeContent() throws Exception {
		log.info(BannerUtils.generateBanner(this, "testBasicDeserializeContent"));

		FileInputStream testContentFile = new FileInputStream(new File(testContentFilePath));
		Content testContent = serializer.deSerializeContent(testContentFile);
		
		assertEquals(new Integer(340051235), testContent.getId());
		assertEquals("article", testContent.getType());
		assertEquals("http://www.guardian.co.uk/media/2008/nov/25/lesleydouglas-bbc", testContent.getWebUrl());
		assertEquals("http://api.guardianapis.com/content/item/340051235", testContent.getApiUrl());
		assertEquals("guardian.co.uk", testContent.getPublication());
		assertEquals("Lesley Douglas to join Universal Music", testContent.getHeadline());
		assertEquals("John Plunkett", testContent.getByline());
		assertEquals("Media", testContent.getSectionName());
		assertEquals(" Former BBC Radio 2 controller Lesley Douglas, who quit the corporation over the 'Sachsgate' affair, is to join Universal Music UK. By John Plunkett ", testContent.getTrailText());
		assertEquals("Lesley Douglas to join Universal Music UK", testContent.getLinkText());
		assertEquals("http://static.guim.co.uk/sys-images/Media/Pix/pictures/2008/10/28/douglas84.jpg", testContent.getTrailImage());
		
		assertNotNull(testContent.getTaggedWith());
		assertNotNull(testContent.getTaggedWith().getTag());
		List<Tag> tagList = testContent.getTaggedWith().getTag();
		assertEquals(10, tagList.size());
		Tag firstContentTag = tagList.get(0);
		
		assertEquals("Business", firstContentTag.getName());
		assertEquals("keyword", firstContentTag.getType());
		assertEquals("/business", firstContentTag.getFilter());
		assertEquals("http://api.guardianapis.com/content/search?filter=/business", firstContentTag.getApiUrl());
		assertEquals("http://www.guardian.co.uk/business", firstContentTag.getWebUrl());
		
		String firstContentItemBody = " Former BBC Radio 2 controller Lesley Douglas, who quit the corporation over the \"Sachsgate\" " +
			"affair, is to join Universal Music UK.  Douglas will become director of programming and business development at the music " + 
			"company, which has a roster of best-selling artists including Amy Winehouse, Duffy and the Killers.  She will take a dual " +
			"programming and marketing role at the company, which she will join on December 8. Douglas will take charge of Universal's " +
			"two-year-old TV division, which has produced ITV music specials featuring Elton John, Girls Aloud and Take That and has " +
			"ambitions to move into comedy and drama.  Douglas will also oversee Universal Music's UK business development strategy, " + 
			"reporting to David Joseph, the chairman and chief executive of Universal Music UK.  Joseph said Douglas would be \"at the " +
			"heart of the evolution and growth of our company\", adding that Universal's artists and staff had \"huge respect and trust " +
			"for her as a broadcaster and above all as someone who lives and breathes music\".  \"She has an exceptional rapport with " + 
			"artists and is simply one of the best media executives and leaders in the business. Lesley ... is joining us to take a dual " +
			"role which will be at the heart of the evolution and growth of our company,\" Joseph said in a message to Universal staff.  " +
			"\"As director of programming, Lesley will drive the development of Globe Productions, our fast-growing TV division. Since its " +
			"launch in 2006, Globe has had many successes including a BBC Paul Weller documentary, Bebo online drama The Secret World of " +
			"Sam King and specials for ITV featuring Elton John, Girls Aloud and Take That.  \"Under Lesley's guidance, Globe's remit will " +
			"extend beyond music properties to dramas and comedies across all media.  \"In addition Lesley will oversee Universal Music's " +
			"UK business development strategy, also reporting to me. This will include non-traditional artist rights, sponsorships and " +
			"strategic marketing partnerships such as the hugely successful pairing of Take That with Marks &amp; Spencer.   \"As we " +
			"continue to diversify our business, I am excited about what Lesley's immense experience, constantly innovative approach and " +
			"fresh perspective can bring to our biggest growth areas.\"  The Universal Music UK head of business development, Mark " +
			"Krendel, and the Globe general manager, Iain Funnell, will report to Douglas.  Douglas was formerly one of the BBC's most " +
			"senior executives and, as its head of pop, was responsible for coordinating music output across BBC TV and radio. She was " +
			"also controller of Radio 2 and BBC 6Music.  She quit at the end of last month in the wake of crisis caused by the lewd phone "+
			"messages left by Radio 2 presenters Russell Brand and Jonathan Ross on actor Andrew Sachs' voicemail as part of Brand's radio " +
			"show.  Douglas will also join Lucian Grainge, the chairman and chief executive of Universal Music Group International, who " +
			"oversees the record company's business outside of America.   Universal had a 33.5% share of the UK music market in the first " +
			"half of 2008, with a stable of artists that also includes U2, Elton John, 50 Cent and Kanye West.  On Friday, it emerged in a " +
			"BBC Trust investigation into the Sachsgate affair that Douglas approved the controversial segment for broadcast on Brand's " +
			"late-night Saturday show with a single-word email sent from her BlackBerry: \"Yes.\"  However, Douglas had not listened to the " +
			"programme before it was broadcast. Brand resigned, as did the station's head of compliance Dave Barber, while Ross was " +
			"suspended for 12 weeks without pay.   Douglas had been controller of Radio 2 since 2003, having previously been deputy to " +
			"her predecessor, Jim Moir. She was also controller of digital music station 6Music.  She was the driving force behind the " +
			"modernisation of Radio 2, the country's most popular station with more than 13 million listeners.  Douglas brought presenters " +
			"such as Chris Evans, Jeremy Vine and the man who would eventually precipitate her downfall - Russell Brand.  &#183; To contact " +
			"the MediaGuardian news desk email editor@mediaguardian.co.uk or phone 020 7239 9857. For all other inquiries please call the " +
			"main Guardian switchboard on 020 7278 2332.  &#183; If you are writing a comment for publication, please mark clearly \"for " +
			"publication\". ";
		
		assertEquals(firstContentItemBody, testContent.getTypeSpecific().getBody());
	}
	
	public void testBasicDeserializeTags() throws Exception {
		log.info(BannerUtils.generateBanner(this, "testBasicDeserializeTags"));

		FileInputStream testTagsFile = new FileInputStream(new File(testTagsFilePath));
		Tags testTags = serializer.deSerializeTags(testTagsFile);
		
		Dumper.dump(testTags);
		assertNotNull(testTags);
		assertEquals(22, testTags.getCount());
		assertEquals(2, testTags.getStartIndex());
		
		assertNotNull(testTags.getTag());
		List<Tag> tagList = testTags.getTag();
		assertEquals(20, tagList.size());
		
		Tag firstTag = tagList.get(0);
		assertEquals("Guildhall School of Music & Drama", firstTag.getName());
		assertEquals("keyword", firstTag.getType());
		assertEquals("/education/guildhall-school-of-music-drama", firstTag.getFilter());
		assertEquals("http://api.guardianapis.com/content/search?filter=/education/guildhall-school-of-music-drama", firstTag.getApiUrl());
		assertEquals("http://www.guardian.co.uk/education/guildhall-school-of-music-drama", firstTag.getWebUrl());
	}
		
}
